package database

import (
	"changeme/internal/models"
	"time"
)

// BuildQueryFromDTO 从DTO构建查询构建器
func BuildQueryFromDTO(dto *models.QueryBuilderDTO) SQLQueryBuilder {
	builder := NewSQLQueryBuilder()

	// 设置列
	if len(dto.Columns) > 0 {
		builder.Select(dto.Columns...)
	}

	// 设置表
	if dto.Table != "" {
		builder.From(dto.Table)
	}

	// 设置WHERE条件
	if len(dto.WhereClause) > 0 && len(dto.WhereClause) == len(dto.WhereArgs)+1 {
		builder.Where(dto.WhereClause[0], dto.WhereArgs...)
		for i := 1; i < len(dto.WhereClause); i++ {
			if i < len(dto.WhereArgs)+1 {
				builder.AndWhere(dto.WhereClause[i], dto.WhereArgs[i-1])
			} else {
				builder.AndWhere(dto.WhereClause[i])
			}
		}
	}

	// 设置JOIN
	for _, join := range dto.Joins {
		builder.Join(join.JoinType, join.Table, join.Condition)
	}

	// 设置GROUP BY
	if len(dto.GroupBy) > 0 {
		builder.GroupBy(dto.GroupBy...)
	}

	// 设置HAVING
	if dto.Having != "" {
		builder.Having(dto.Having, dto.HavingArgs...)
	}

	// 设置ORDER BY
	for _, order := range dto.OrderBy {
		// 假设order字符串格式为"column ASC"或"column DESC"
		parts := splitOrderBy(order)
		if len(parts) == 2 {
			builder.OrderBy(parts[0], parts[1])
		}
	}

	// 设置LIMIT和OFFSET
	if dto.LimitVal != nil {
		builder.Limit(*dto.LimitVal)
	}
	if dto.OffsetVal != nil {
		builder.Offset(*dto.OffsetVal)
	}

	return builder
}

// ConvertToErrorDTO 将数据库错误转换为DTO
func ConvertToErrorDTO(err *DatabaseError) *models.DatabaseErrorDTO {
	if err == nil {
		return nil
	}

	return &models.DatabaseErrorDTO{
		Message:       err.Message,
		Code:          string(err.Code),
		SQLState:      err.GetSQLState(),
		DBType:        err.DBType,
		IsConstraint:  err.IsConstraintViolation(),
		IsRetryable:   err.IsRetryable(),
		Query:         err.Query,
		OriginalError: err.Error(),
		Timestamp:     err.Timestamp.Format(time.RFC3339),
	}
}

// CreateErrorFromString 从错误字符串创建数据库错误
func CreateErrorFromString(errorStr string, dbType models.DatabaseType) *DatabaseError {
	if errorStr == "" {
		return nil
	}

	// 创建一个简单的数据库错误
	return &DatabaseError{
		Code:      ErrCodeUnknown,
		Message:   errorStr,
		DBType:    dbType,
		Timestamp: time.Now(),
	}
}

// 辅助函数，分割ORDER BY子句
func splitOrderBy(orderBy string) []string {
	// 这个实现可以根据实际需求进行调整
	// 假设最后一个空格分隔符之后是ASC/DESC
	parts := []string{orderBy, "ASC"} // 默认值

	// 如果字符串包含"ASC"或"DESC"
	if len(orderBy) > 5 {
		lastPart := orderBy[len(orderBy)-5:]
		if lastPart == " DESC" {
			parts[0] = orderBy[:len(orderBy)-5]
			parts[1] = "DESC"
		} else if len(orderBy) > 4 && orderBy[len(orderBy)-4:] == " ASC" {
			parts[0] = orderBy[:len(orderBy)-4]
			parts[1] = "ASC"
		}
	}

	return parts
}
